import React, { useImperativeHandle, useRef, useState } from 'react';
import classNames from 'classnames';
import { Image } from '@tarojs/components';
import { CouponSelectPop, CouponSelectPopRefType } from '@/components';
import styles from './index.module.less';
import { useMovieStore } from '@/common/hox/movieStore';
import { CouponBatchStatusEnum } from '@/utils/enum';
import { TicketModeEnum } from '@/utils/enum';

type CouponSelectPropsType = {
    className?: string;
    onCouponListGroupChange?: Parameters<typeof CouponSelectPop>[0]['onCouponListGroupChange'];
};
function CouponSelect(
    props: CouponSelectPropsType,
    ref: React.ForwardedRef<CouponSelectPopRefType>
) {
    const { className, onCouponListGroupChange } = props;
    const couponSelectPopRef = useRef<CouponSelectPopRefType>(null);
    const {
        movie: { movieDetail },
        coupon: { selectCoupon, setSelectCoupon },
        seat: { seatTotalPrice, seatList },
        schedule: { scheduleDetail, issueTicketMode },
    } = useMovieStore((store) => [
        store.coupon.couponList,
        store.coupon.selectCoupon,
        store.coupon.setSelectCoupon,
        store.cinema.cinemaInfo,
        store.movie.movieDetail,
        store.seat.seatTotalPrice,
        store.seat.seatList,
        store.schedule.scheduleDetail,
        store.schedule.scheduleSeatInfo,
        store.schedule.issueTicketMode,
        store.schedule.acceptChangeSeat,
    ]);

    const [availableCoupon, setAvailableCoupon] = useState<Coupon.ListItem[]>([]);
    const [isOpen, setIsOpen] = useState<Boolean>(false);
    useImperativeHandle(ref, () => ({
        open: () => couponSelectPopRef.current?.open(),
    }));

    if (!scheduleDetail || !movieDetail) return null;

    const hasAvailableCoupon = Boolean(availableCoupon.length || 0);
    if (hasAvailableCoupon && !isOpen && !selectCoupon) {
        setSelectCoupon(availableCoupon[0]);
    }

    return (
        <>
            <div
                className={classNames(className, styles.couponCard)}
                onClick={() => {
                    setIsOpen(true);
                    couponSelectPopRef.current?.open();
                }}
            >
                <div className={styles.title}>优惠券&活动</div>
                <div
                    className={classNames(styles.arrow, {
                        [styles.hasAvailableCoupon]: hasAvailableCoupon,
                    })}
                >
                    {hasAvailableCoupon
                        ? selectCoupon
                            ? `-￥${
                                  selectCoupon.couponType === 1
                                      ? seatTotalPrice.seatItemPrice
                                      : selectCoupon.batchValue
                              }`
                            : `${availableCoupon.length}张优惠券可用`
                        : `暂无可用`}
                    <Image
                        className={styles.arrowIcon}
                        src="https://fulu-media.oss-cn-hangzhou.aliyuncs.com/public/icon/weui--arrow-filled.png"
                    />
                </div>
            </div>
            <CouponSelectPop
                ref={couponSelectPopRef}
                cinemaCode={scheduleDetail.cinemaId}
                moveCode={movieDetail.movieCode}
                hall={scheduleDetail.hallName}
                showTime={scheduleDetail.showTime}
                showId={scheduleDetail.showId}
                version={scheduleDetail.versionTypes}
                originPrice={scheduleDetail.originPrice}
                publishPrice={scheduleDetail.publishPrice}
                fastTicket={issueTicketMode === TicketModeEnum.FastTicket}
                buyNum={seatList.length}
                selectedCouponCode={selectCoupon?.couponCode}
                onSelect={setSelectCoupon}
                orderQuantity={seatList.length}
                onCouponListGroupChange={(groupData) => {
                    setAvailableCoupon(
                        groupData.find(([key]) => key === CouponBatchStatusEnum.enable)?.[1] || []
                    );
                    onCouponListGroupChange?.(groupData);
                }}
            />
        </>
    );
}

export default React.forwardRef(CouponSelect);
